#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib, urllib2


## ---- Global data

DEFAULT_ENCODING = 'utf-8'


## ---- Helper funcs

def safeunicode(obj, encoding=DEFAULT_ENCODING):
    if isinstance(obj, unicode):
        return obj
    elif isinstance(obj, str):
        return obj.decode(encoding)
    else:
        return unicode(obj)


def safestr(obj, encoding=DEFAULT_ENCODING):
    if isinstance(obj, unicode):
        return obj.encode(encoding)
    elif isinstance(obj, str):
        return obj
    else:
        return str(obj)


def escape_html(text):
    """Escape &, <, > as well as single and double quotes for HTML."""
    return text.replace('&', '&amp;').  \
                replace('<', '&lt;').   \
                replace('>', '&gt;').   \
                replace('"', '&quot;'). \
                replace("'", '&#39;')


def build_data(tpl, encoding=DEFAULT_ENCODING, **kw):
    from string import Template as T

    t = T(tpl)
    for k, v in kw.items():
        kw[k] = urllib.quote_plus(safestr(v, encoding))
    return t.safe_substitute(kw)


def ungzip(res):
    import StringIO
    import gzip

    header_dict = res.info()
    data = res.read()
    encoding = header_dict.get('Content-Encoding', None)
    if encoding and encoding.find('gzip') != -1:
        data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read()
    return data


def get_helper(get_url, get_data=None):
    try:
        req = urllib2.Request(get_url)
        req.add_header('Accept-Encoding', 'gzip, deflate')
        if get_data:
            res = urllib2.urlopen(req, get_data)
        else:
            res = urllib2.urlopen(req)
        return res
    except Exception, e:
        print e
        return None


def post_helper(post_url, post_data):
    try:
        req = urllib2.Request(post_url)
        req.add_header('Content-Type', 'application/x-www-form-urlencoded')
        req.add_header('Accept-Encoding', 'gzip, deflate')
        res = urllib2.urlopen(req, post_data)
        return res
    except:
        return None

